package com.magic.gre.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.magic.gre.R;
import com.magic.gre.adapter.AnswerItemAdapter;
import com.magic.gre.base.activity.BaseMVPActivity;
import com.magic.gre.entity.AnswerBean;
import com.magic.gre.entity.AnswerItemBean;
import com.magic.gre.mvp.contract.AnswerContract;
import com.magic.gre.mvp.presenter.AnswerPresenrerImpl;
import com.magic.gre.ui.dialog.AnswerDialog;
import com.magic.gre.ui.dialog.WordsDetailsDialog;
import com.magic.gre.utils.PermissonUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Author: Lmoumou
 * Date: 2019-01-08 19:11
 * 文件名: AnswerActivity
 * 描述:
 */
public class AnswerActivity extends BaseMVPActivity<AnswerPresenrerImpl> implements AnswerContract.View,
        AnswerItemAdapter.OnAnswerItemClickListener, AnswerDialog.OnAnserDialogLiatener {
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.up_tv)
    TextView upTv;

    public static void startThis(Context context, String unitId) {
        Intent intent = new Intent(context.getApplicationContext(), AnswerActivity.class);
        intent.putExtra("unitId", unitId);
        context.startActivity(intent);
    }

    private AnswerItemAdapter adapter;
    private List<AnswerItemBean> dataList = new ArrayList<>();
    private List<AnswerBean> answerList = new ArrayList<>();
    private Handler handler = new Handler();
    private int posiiton = 1;
    private AnswerDialog answerDialog;
    private TextView titleTv;
    private String unitId;
    private AnswerBean currentAnswerBean;
    private RxPermissions rxPermissions;

    /*开始时间*/
    private long startTime = 0;
    /*答题所用时间*/
    private long answerTime = 0;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_answer;
    }

    @Override
    protected AnswerPresenrerImpl creatPresenter() {
        return new AnswerPresenrerImpl(this);
    }

    @Override
    protected void netOverride() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        startTime = System.currentTimeMillis();
    }

    @Override
    protected void onPause() {
        super.onPause();
        answerTime += (System.currentTimeMillis() - startTime);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        unitId = getIntent().getStringExtra("unitId");

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }

            @Override
            public boolean canScrollVertically() {
                return true;
            }
        });

        adapter = new AnswerItemAdapter(this, dataList);
        adapter.setOnAnswerItemClickListener(this);
        mRecyclerView.setAdapter(adapter);

        mPresenter.pGetSubs(unitId);
    }

    @SuppressLint("SetTextI18n")
    @OnClick(value = {R.id.up_tv})
    protected void onClick(View view) {
        switch (view.getId()) {
            case R.id.up_tv://上一题
                if (answerDialog != null) {
                    answerDialog.dismissThis(answerDialog.isResumed());
                }

                dataList.clear();
                posiiton--;
                final AnswerBean answerBean = AnswerActivity.this.answerList.get(posiiton - 1);
                dataList.addAll(answerBean.getSubItems());
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                        upDataUI(answerBean);
                        showAnswerDialog();
                    }
                }, 500);

                break;
        }
    }

    /**
     * 胡pda正确
     */
    @Override
    public void onCheckYes() {
        this.currentAnswerBean.setAnswer(true);
        nextTopic();
    }

    @Override
    public void onTitleTv(TextView textView) {
        this.titleTv = textView;
    }

    /**
     * 回答错误
     *
     * @param position
     */
    @Override
    public void onCheckNo(int position) {
        this.currentAnswerBean.setAnswer(true);
        showAnswerDialog();
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 下一题
     */
    @Override
    public void onNext() {
        nextTopic();
    }

    /**
     * 查看单词详情
     *
     * @param answerBean
     */
    @Override
    public void onDetails(AnswerBean answerBean) {
        WordsDetailsDialog detailsDialog = new WordsDetailsDialog();
        detailsDialog.showThis(getSupportFragmentManager(), WordsDetailsDialog.class.getSimpleName(), answerBean);
    }

    /**
     * 获取数据
     *
     * @param beanList
     */
    @Override
    public void vGetSubs(List<AnswerBean> beanList) {
        this.answerList.clear();
        this.answerList.addAll(beanList);
        if (!this.answerList.isEmpty()) {
            upDataUI(this.answerList.get(0));
        }
    }

    @Override
    public void vSumbitResult(String id) {
        AnswerFinishActivity.startThis(AnswerActivity.this, id);
        AnswerActivity.this.finish();
    }

    /**
     * 更新ui
     *
     * @param answerBean
     */
    @SuppressLint("SetTextI18n")
    private void upDataUI(AnswerBean answerBean) {
        this.currentAnswerBean = answerBean;
        tvTitle.setText(String.valueOf(posiiton) + "/" + String.valueOf(this.answerList.size()));
        if (titleTv != null) {
            titleTv.setText(answerBean.getName());
        }
        dataList.clear();
        dataList.addAll(answerBean.getSubItems());
        adapter.notifyDataSetChanged();
        upTv.setEnabled(posiiton > 1);
        upTv.setVisibility(posiiton > 1 ? View.VISIBLE : View.INVISIBLE);
    }

    /**
     * 显示单词1级弹窗
     */
    @SuppressLint("CheckResult")
    private void showAnswerDialog() {
        if (answerDialog == null) {
            answerDialog = new AnswerDialog();
            answerDialog.setOnAnserDialogLiatener(this);
        }

        if (rxPermissions==null){
            rxPermissions=new RxPermissions(this);
        }

        rxPermissions.request(PermissonUtils.VOICE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean){
                            if (posiiton >= AnswerActivity.this.answerList.size()) {
                                answerDialog.showThis(getSupportFragmentManager(), AnswerDialog.class.getSimpleName(), currentAnswerBean,"查看结果");
                            } else {
                                answerDialog.showThis(getSupportFragmentManager(), AnswerDialog.class.getSimpleName(), currentAnswerBean,"下一题");
                            }
                        }
                    }
                });


    }

    /**
     * 下一题
     */
    private void nextTopic() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (posiiton >= AnswerActivity.this.answerList.size()) {
                    answerTime += (System.currentTimeMillis() - startTime);
                    mPresenter.pSumbitResult(unitId, getRightAnswer().size(), answerTime,answerList.size());
                } else {
                    dataList.clear();
                    posiiton++;
                    AnswerBean answerBean = AnswerActivity.this.answerList.get(posiiton - 1);
                    dataList.addAll(answerBean.getSubItems());
                    adapter.notifyDataSetChanged();
                    upDataUI(answerBean);
                    if (currentAnswerBean.isAnswer()) {//如果这道题回答过，显示答案弹窗
                        showAnswerDialog();
                    }
                }

            }
        }, 500);
    }

    private List<AnswerItemBean> getRightAnswer() {
        List<AnswerItemBean> rightList = new ArrayList<>();

        m:
        for (AnswerBean answerBean : answerList) {
            n:
            for (AnswerItemBean answerItemBean : answerBean.getSubItems()) {
                if (answerItemBean.getTag() == 1) {
                    rightList.add(answerItemBean);
                    continue m;
                }
            }
        }
        return rightList;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
